<template>
  <div class="LabelIssueComponent">
    <div style="font-size: 16px;">{{ message }}</div>
    <div style="margin-top: 20px;margin-right: 20px">
      <el-button type="primary" @click="startIssue" :disabled="executed" style="float: right;right: 20px">发行（打印）
      </el-button>
    </div>
    <el-table
      :data="form"
      style="margin-top: 60px"
      header-cell-class-name="table-header"
      show-overflow-tooltip>
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="tagId"
        label="标签ID">
      </el-table-column>
      <el-table-column
        label="状态"
        width="50">
        <template slot-scope='scope'>
          <el-icon v-if="scope.row.status==1" class="el-icon-success"/>
          <el-icon v-else-if="scope.row.status==0" class="el-icon-error"/>
          <el-icon v-else-if="scope.row.status==2" class="el-icon-loading"/>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { confirmLabelIssue } from '@/api/purchase'
import { getConn, relConn, writeCode } from '@/api/epc'

export default {
  name: 'LabelIssueComponent',
  components: {},
  props: {
    message: {
      type: String,
      default: ''
    },
    form: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      // 只执行一次
      executed: false,
      currentIndex: 0
    }
  },
  mounted() {
  },
  destroyed() {
    // 退出的时候，执行一次释放连接
    relConn().then(res => {
    })
  },
  methods: {
    startIssue() {
      getConn().then(res => {
        if (res.success) {
          // 获取读卡器连接成功
          // 先把所有状态都设为loading
          this.form.forEach(item => {
            item.status = '2'
          })
          this.executed = true
          this.startWriteEpc()
        } else {
          this.executed = false
          this.$message({
            type: 'error',
            message: res.rMsg
          })
        }
      })
    },
    startWriteEpc() {
      const param = { code: this.form[this.currentIndex] }
      writeCode(param).then(res => {
        if (res.success) {
          // 设置状态为完成
          this.form[this.currentIndex].status = '1'
          // 通知服务器该标签已经发行
          confirmLabelIssue({ tagId: this.form[this.currentIndex].tagId }).then(res => {
            // 无论通知成功与否，不管
          })
        } else {
          // 设置状态为失败
          this.form[this.currentIndex].status = '0'
        }
        this.currentIndex++
        if (this.currentIndex >= this.form.length) {
          // 全部执行完毕, 释放连接
          relConn().then(res => {
          })
        } else {
          // 执行下一个
          this.startWriteEpc()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.LabelIssueComponent {
  box-sizing: border-box;
  padding: 0px 50px;
}
</style>
